package cn.hasayam.test3;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Record {
    //是否在录制
    private boolean isRecording = false;
    //pcm文件
    private File file;

    public static final String TAG = "PCMSample";

    private RecordCall recoudCall;

    public void lala(RecordCall lalaRecourd){
        this.recoudCall = lalaRecourd;
    }

    public void run(){
        if (recoudCall != null){
            RecordFuck recordFuck = new RecordFuck(this);
            this.recoudCall.dorun(recordFuck);
        }
    }
    public void ling(){
        if (recoudCall != null){
            RecordFuck recordFuck = new RecordFuck(this);
            this.recoudCall.doling(recordFuck);
        }
    }
    public void not(){
        if (recoudCall != null){
            RecordFuck recordFuck = new RecordFuck(this);
            this.recoudCall.donot(recordFuck);
        }
    }
    public void Start(){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG,"开始录音");
                int frequency = 16000;
                int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
                int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
                file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/temp.pcm");
                Log.i(TAG,"生成文件");
                //如果存在，就先删除再创建
                if (file.exists()) {
                    file.delete();
                    Log.i(TAG, "删除文件");
                }
                try {
                    file.createNewFile();
                    Log.i(TAG,"创建文件");
                } catch (IOException e) {
                    Log.i(TAG,"未能创建");
                    throw new IllegalStateException("未能创建" + file.toString());
                }
                try {
                    //输出流
                    OutputStream os = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(os);
                    DataOutputStream dos = new DataOutputStream(bos);
                    int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
                    AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize);

                    short[] buffer = new short[bufferSize];
                    audioRecord.startRecording();
                    Log.i(TAG, "开始录音");
                    int count = 0;
                    isRecording = true;
                    while (isRecording) {
                        int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
                        int v = 0;
                        for (int i = 0; i<buffer.length; i++){
                            v += buffer[i] * buffer[i];
                        }
                        int value = (int) (Math.abs((int)(v /(float)bufferReadResult)/10000) >> 1);
                        //Log.d("音量", String.valueOf(value));
                        if (value == 0){
                            count++;
                            ling();
                            //Log.d("静音时间", String.valueOf(count));
                        }else{
                            count = 0;
                            not();
                        }
                        for (int i = 0; i < bufferReadResult; i++) {
                            dos.writeShort(buffer[i]);
                        }
                        if (count == 25){
                            Stop();
                            Record.this.run();
                        }
                    }
                    audioRecord.stop();
                    dos.close();
                } catch (Throwable t) {
                    Log.e(TAG, "录音失败");
                }
                Log.e(TAG,"start");
            }
        });
        thread.start();
    }

    public void Stop(){
        isRecording = false;
    }

    public void Play(){
        if(file == null){
            return;
        }
        //读取文件
        int musicLength = (int) (file.length() / 2);
        short[] music = new short[musicLength];
        try {
            InputStream is = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);
            int i = 0;
            while (dis.available() > 0) {
                music[i] = dis.readShort();
                i++;
            }
            dis.close();
            AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    16000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    musicLength * 2,
                    AudioTrack.MODE_STREAM);
            audioTrack.play();
            audioTrack.write(music, 0, musicLength);
            audioTrack.stop();
        } catch (Throwable t) {
            Log.e(TAG, "播放失败");
        }
    }

    public void Delete(){
        if(file == null){
            return;
        }
        file.delete();
    }
}
